const R = require('ramda')
const ValidatorError = require('../errors/ValidatorError')
const Schema = require('async-validator').default
const getFirstErrorMessage = R.compose(
  R.prop('message'),
  R.head,
  R.prop('errors')
)
class ValueObject {
  constructor(descriptor) {
    if (descriptor) {
      Object.defineProperty(this, '_descriptor', {
        value: descriptor,
        writable: false,
        enumerable: false,
      })
    }
  }
  async validate() {
    const validator = new Schema(this._descriptor)
    try {
      await validator.validate(this)
    } catch (error) {
      throw new ValidatorError(getFirstErrorMessage(error))
    }
  }
}

module.exports = ValueObject
